/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package client.process;

/**
 *
 * @author ghufron
 */
import java.io.*;
import java.net.*;

public class RepoClient implements Runnable{
    // Declaration section
    // clientClient: the client socket
    // os: the output stream
    // is: the input stream

    static Socket clientSocket = null;
    static PrintStream os = null;
    static DataInputStream is = null;
    static BufferedReader inputLine = null;
    static boolean closed = false;
    static String perintah = null;

    public void mulai() {

	// The default port

	int port_number=6211;
        String host="localhost";

	//if (args.length < 2)
	    //{
		System.out.println("Usage: java RepositoryClient  \n"+
				   "Now using host="+host+", port_number="+port_number);
	    //} else {
		//host=args[0];
		//port_number=Integer.valueOf(args[1]).intValue();
	    //}
	// Initialization section:
	// Try to open a socket on a given host and port
	// Try to open input and output streams
	try {
            clientSocket = new Socket(host, port_number);
            inputLine = new BufferedReader(new InputStreamReader(System.in));
            os = new PrintStream(clientSocket.getOutputStream());
            is = new DataInputStream(clientSocket.getInputStream());
        } catch (UnknownHostException e) {
            System.err.println("Don't know about host "+host);
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for the connection to the host "+host);
        }

	// If everything has been initialized then we want to write some data
	// to the socket we have opened a connection to on port port_number

        if (clientSocket != null && os != null && is != null) {
            try {

		// Create a thread to read from the server

                new Thread(new RepoClient()).start();

		while (!closed) {
                    //dikasih fungsi buat ngegenerate perintah (login, direktori, cek, update, commit)
                    os.println(perintah);
                }

		// Clean up:
		// close the output stream
		// close the input stream
		// close the socket

		os.close();
		is.close();
		clientSocket.close();
            } catch (IOException e) {
                System.err.println("IOException:  " + e);
            }
        }
    }

    public String genRequestLogin(){
        return "login";
    }

    public String genRequestdirClient(){
        return "direktori client";
    }

    public String genRequestdirServer(){
        return "direktori server";
    }

    public String genRequestCek(){
        return "cek";
    }

    public String genRequestUpdate(){
        return "update";
    }

    public String genRequestCommit(){
        return "commit";
    }

    public void terimaFile(String namafile) throws IOException{
        //long start = System.currentTimeMillis();
        int bytesRead;
        int current = 0;
        // localhost for testing
        //Socket sock = new Socket("127.0.0.1",13267);
        System.out.println("Connecting...");

        // receive file
        InputStream input = clientSocket.getInputStream();
        int filesize = input.read();
        byte [] mybytearray  = new byte [filesize];
        //InputStream is = sock.getInputStream();
        FileOutputStream fos = new FileOutputStream(namafile);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        bytesRead = input.read(mybytearray,0,mybytearray.length);
        current = bytesRead;

        // thanks to A. Cádiz for the bug fix
        do {
           bytesRead =
              input.read(mybytearray, current, (mybytearray.length-current));
           if(bytesRead >= 0) current += bytesRead;
        } while(bytesRead > -1);

        bos.write(mybytearray, 0 , current);
        bos.flush();
        //long end = System.currentTimeMillis();
        //System.out.println(end-start);
        bos.close();
        //sock.close();

    }

    public void run() {
	String responseLine;

	// Keep on reading from the socket till we receive the "Bye" from the server,
	// once we received that then we want to break.
	try{
            BufferedReader br=new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
	    while ((responseLine = is.readLine()) != null) {
		System.out.println(responseLine);
		if (responseLine.indexOf("Sambungan") != -1) break;
	    }
            closed=true;
	} catch (IOException e) {
            e.printStackTrace();
	    System.err.println("zzzzIOException:  " + e);
	}
    }
}
